package saucaca.Service;

import saucaca.Object.SongObject;
import saucaca.Util.AppController;
import saucaca.Util.UtilMusic;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.RemoteControlClient;
import android.media.RemoteControlClient.MetadataEditor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;

@SuppressLint("NewApi")
public class MusicService extends Service implements AudioManager.OnAudioFocusChangeListener, OnPreparedListener, OnCompletionListener, OnErrorListener {

	private static final String TAG = "saucaca.Service_MusicService";
	public static final String PREF_NAME = "MAINPLAYER";
	public static final String SETTING_SHUFFLE = "SHUFFLE";
	public static final String SETTING_REPEAT = "REPEAT";
	// Intent action
	public static final String ACTION_TOGGLE_PLAYBACK = "saucaca.Service.TOGGLE_PLAYBACK";
	public static final String ACTION_PLAY = "saucaca.Service.PLAY";
	public static final String ACTION_PREVIOUS = "saucaca.Service.PREVIOUS";
	public static final String ACTION_NEXT = "saucaca.Service.NEXT";
	public static final String ACTION_PAUSE = "saucaca.Service.PAUSE";
	public static final String ACTION_DELETE = "saucaca.Service.DELETE";
	public static final String ACTION_SEEK = "saucaca.Service.SEEK";
	public static final String SUPPLY_PLAYLIST = "saucaca.Service.SUPPLY_PLAYLIST";
	public static final String ACTION_PLAY_SPECIFIC_SONG = "saucaca.Service.PLAY_SPECIFIC_SONG";
	public static final String ACTION_TOGGLE_REPEATMODE = "saucaca.Service.TOGGLE_REPEATMODE";
	public static final String ACTION_TOGGLE_SHUFFLE = "saucaca.Service.TOGGLE_SHUFFLE";
	public static final String REQUEST_STATUS = "saucaca.Service.REQUEST_STATUS";
	public static final String ACTION_REORDER_PLAYLIST = "saucaca.Service.REORDER_PLAYLIST";
	public static final String ACTION_SETUP_AS_FOREGROUND = "saucaca.Service.SETUP_AS_FOREGROUND";

	// Bundle key string
	public static final String BKEY_PLAYLIST = "PLAYLIST";
	public static final String BKEY_PLAYSONG = "PLAYSONG";
	public static final String BKEY_STATE = "MEDIAPLAYER_STATE";
	public static final String BKEY_CURSONG_DURATION = "SONG_DURATION";
	public static final String BKEY_CURSONG_POSITION = "SONG_POSITION";
	public static final String BKEY_PERCENTAGE = "PERCENTAGE";
	public static final String BKEY_REPEATMODE = "REPEAT_MODE";
	public static final String BKEY_SHUFFLE = "SHUFFLE";
	public static final String BKEY_REORDER_FROM = "REORDER_FROM";
	public static final String BKEY_REORDER_TO = "REORDER_TO";

	// Broadcast status action
	public static final String STATUS_BC_NOW_PLAYING = "saucaca.Service.NOW_PLAYING";
	public static final String STATUS_BC_PLAYTIME = "saucaca.Service.PLAYTIME";
	public static final String STATUS_BC_ALL = "saucaca.Service.ALLSTATUS";
	public static final String STATUS_BC_PLAYMODE = "saucaca.Service.PLAYMODE";
	public static final String STATUS_BC_NOWPLAYING_PLAYLIST = "saucaca.Service.NOWPLAYING_PLAYLIST";

	//
	public static final String CMDNOTIF = "buttonId";
	// Media player
	private MediaPlayer mMediaPlayer = null;

	// Media state
	public enum MediaPlayerState {
		Stopped, Preparing, Playing, Paused
	}

	public static MediaPlayerState mState = MediaPlayerState.Stopped;

	// Playlist playing for this Music service
	private static PlaylistManager mPlaylistMgr = null;

	// SongItem current playing
	private SongObject playItem = null;

	// Handler xu ly cap nhat timer
	private Handler mHandler;
	private int mUpdateInterval = 500;
	private float mDuckVolume = 0.5f;

	// Error continue
	private int mAttempCount = 0;

	private ComponentName remoteComponentName;
	private RemoteControlClient remoteControlClient;
	AudioManager audioManager;
	private static boolean currentVersionSupportBigNotification = false;
	private static boolean currentVersionSupportLockScreenControls = false;
	int NOTIFICATION_ID = 1111;

	@SuppressLint("NewApi")
	@Override
	public void onCreate() {
		mState = MediaPlayerState.Stopped;
		mHandler = new Handler();

		audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		currentVersionSupportBigNotification = currentVersionSupportBigNotification();
		currentVersionSupportLockScreenControls = currentVersionSupportLockScreenControls();
	}

	public static boolean currentVersionSupportBigNotification() {
		int sdkVersion = android.os.Build.VERSION.SDK_INT;
		if (sdkVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
			return true;
		}
		return false;
	}

	public static boolean currentVersionSupportLockScreenControls() {
		int sdkVersion = android.os.Build.VERSION.SDK_INT;
		if (sdkVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			return true;
		}
		return false;
	}

	public void onDestroy() {
		Log.i(TAG, "onDestroy");
		// Service is being killed, so make sure we release our resources
		mState = MediaPlayerState.Stopped;
		relaxResources(true);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public static PlaylistManager getPlaylistManager() {
		return mPlaylistMgr;
	}

	public static MediaPlayerState getState() {
		return mState;
	}

	@SuppressLint("NewApi")
	public int onStartCommand(Intent i, int flags, int startID) {
		String action = i.getAction();
		Log.i(TAG, "intent:" + action);

		if (action.equals(SUPPLY_PLAYLIST)) {
			retrievePlaylist();
			return START_NOT_STICKY;
		}

		if (action.equals(REQUEST_STATUS)) {
			requestStatus();
		} else {
			// check if playlist is null?
			if (mPlaylistMgr == null)
				return START_NOT_STICKY;

			if (action.equals(ACTION_PLAY))
				processPlayRequest();
			else if (action.equals(ACTION_NEXT))
				processNextRequest();
			else if (action.equals(ACTION_PREVIOUS))
				processPreviousRequest();
			else if (action.equals(ACTION_TOGGLE_PLAYBACK))
				processTogglePlaybackRequest();
			else if (action.equals(ACTION_PLAY_SPECIFIC_SONG))
				processPlaySpecificSong();
			else if (action.equals(ACTION_PAUSE))
				processPauseRequest();
			else if (action.equals(ACTION_SEEK))
				processSeek(i);
			if (action.equals(ACTION_DELETE)) {
				processPauseRequest();
				processStopRequest(true);
			}
			// else if (action.equals(ACTION_TOGGLE_SHUFFLE) ||
			// action.equals(ACTION_TOGGLE_REPEATMODE))
			// processTogglePlaymode();
			else if (action.equals(ACTION_REORDER_PLAYLIST))
				processReorderPlaylist();
			newNotification();
			if (currentVersionSupportLockScreenControls) {
				RegisterRemoteClient();
			}
		}

		return START_NOT_STICKY;

	}

	private void processReorderPlaylist() {
		// try to refresh current song playing index
		mPlaylistMgr.setCurrentSong(playItem);
	}

	private void requestStatus() {
		// stop foreground of service if application came into foreground
		sendStatus(STATUS_BC_ALL);
	}

	private void retrievePlaylist() {
		Singleton s = Singleton.getInstance();
		mPlaylistMgr = s.getPlaylistManager();
	}

	private void processPlaySpecificSong() {
		if (mState == MediaPlayerState.Preparing) {
			relaxResources(false);
		}
		Singleton singleton = Singleton.getInstance();
		SongObject si = singleton.getCurrentSongObject();

		if (mPlaylistMgr.setCurrentSong(si))
			playSong(si);
	}

	private void processTogglePlaybackRequest() {
		if (mState == MediaPlayerState.Paused || mState == MediaPlayerState.Stopped)
			processPlayRequest();
		else
			processPauseRequest();
	}

	private void processPlayRequest() {
		if (mState == MediaPlayerState.Stopped) {
			playSong(mPlaylistMgr.gotoNextSong());
		} else if (mState == MediaPlayerState.Paused) {
			mState = MediaPlayerState.Playing;
			// mNotificationHelper.bringServiceToForeground();
			configAndStartMediaPlayer();
		}
	}

	private void processPauseRequest() {
		if (mState == MediaPlayerState.Playing) {
			mState = MediaPlayerState.Paused;
			mMediaPlayer.pause();
			mPlaylistMgr.currentDuration = mMediaPlayer.getCurrentPosition();
			sendStatus(STATUS_BC_NOW_PLAYING);
			relaxResources(false);
		}
	}

	private void processPreviousRequest() {
		if (mState == MediaPlayerState.Playing || mState == MediaPlayerState.Paused) {
			// if (mPlaylistMgr.gotoPreviousSong() != null)
			playSong(mPlaylistMgr.gotoPreviousSong());
		}
	}

	private void processNextRequest() {
		if (mState == MediaPlayerState.Playing || mState == MediaPlayerState.Paused) {
			playSong(mPlaylistMgr.gotoNextSong());
		}
	}

	private void processSeek(Intent i) {
		if ((mState != MediaPlayerState.Playing) && (mState != MediaPlayerState.Paused))
			return;
		Bundle b = i.getExtras();
		int pos = UtilMusic.percentageToPosition(b.getInt(BKEY_PERCENTAGE), mMediaPlayer.getDuration());
		mMediaPlayer.seekTo(pos);
	}

	private void processStopRequest(boolean force) {
		if (mState == MediaPlayerState.Playing || mState == MediaPlayerState.Paused || force) {
			mState = MediaPlayerState.Stopped;

			// let go of all resources...
			relaxResources(true);
			// mAudioFocusHelper.abandonFocus();

			// service is no longer necessary. Will be started again if needed.
			stopSelf();
		}

	}

	@SuppressLint("NewApi")
	public void onPrepared(MediaPlayer mp) {
		Log.i(TAG, "onPrepared");
		mState = MediaPlayerState.Playing;
		if (currentVersionSupportLockScreenControls) {
			UpdateMetadata();
			remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
		}
		configAndStartMediaPlayer();
	}

	public boolean onError(MediaPlayer mp, int what, int extra) {
		// Log.e(TAG, "Error: what=" + String.valueOf(what) + ", extra=" +
		// String.valueOf(extra));
		mState = MediaPlayerState.Stopped;
		relaxResources(true);

		if (mAttempCount < 2) {
			mAttempCount += 1;
			Toast.makeText(getApplicationContext(), "Error playing! Trying next song. ", Toast.LENGTH_SHORT).show();
			processPlayRequest(); // attempt to play next song
		} else { // reset and do nothing
			Toast.makeText(getApplicationContext(), "Error! Stop. ", Toast.LENGTH_SHORT).show();
			mAttempCount = 0;
		}

		return true;
	}

	public void onCompletion(MediaPlayer mp) {
		playSong(mPlaylistMgr.gotoNextSong());
	}

	private void createMediaPlayerIfNeeded() {
		Log.i(TAG, "Create mediaplayer now is:" + String.valueOf(mMediaPlayer));
		if (mMediaPlayer == null) {
			mMediaPlayer = new MediaPlayer();

			// make mediaplayer wakelock
			mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
			mMediaPlayer.setOnPreparedListener(this);
			mMediaPlayer.setOnCompletionListener(this);
			mMediaPlayer.setOnErrorListener(this);
		} else
			mMediaPlayer.reset();
	}

	/**
	 * Releases resources used by the service for playback. This includes the
	 * "foreground service" status and notification, the wake locks and possibly
	 * the MediaPlayer.
	 * 
	 * @param releaseMediaPlayer
	 *            Indicates whether the Media Player should also be released or
	 *            not
	 */
	void relaxResources(boolean releaseMediaPlayer) {

		// stop being a foreground service
		stopForeground(true);

		// stop update playing time to activity
		stopUpdatePlaytime();

		// stop and release the Media Player, if it's available
		if (releaseMediaPlayer && mMediaPlayer != null) {
			mMediaPlayer.reset();
			mMediaPlayer.release();
			mMediaPlayer = null;
		}

	}

	@SuppressLint("NewApi")
	private void playSong(SongObject si) {
		mState = MediaPlayerState.Stopped;
		relaxResources(false);
		// mAudioFocusHelper.requestFocus();
		try {
			playItem = si;
			if (playItem == null) {
				// Toast.makeText(this,
				// "No available music to play. Place some music on your external storage "
				// + "device (e.g. your SD card) and try again.",
				// Toast.LENGTH_LONG).show();
				processStopRequest(true); // stop everything!
				return;
			}
			createMediaPlayerIfNeeded();
			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mMediaPlayer.setDataSource(getApplicationContext(), Uri.parse(BaseEngine.checkVideoPath(playItem.getPATCH_FULL())));

			mState = MediaPlayerState.Preparing;
			mMediaPlayer.prepareAsync();
		} catch (Exception ex) {
			Log.e("MusicService", "IOException playing next song: " + ex.getMessage());
			ex.printStackTrace();
		}
	}

	private void configAndStartMediaPlayer() {
		if (mMediaPlayer.isPlaying() == false) {
			mState = MediaPlayerState.Playing;
			mMediaPlayer.start();
			// mNotificationHelper.bringServiceToForeground();
			startUpdatePlaytime();
			sendStatus(STATUS_BC_NOW_PLAYING);
		}
	}

	/**
	 * Send broadcast media playing status Any activity can receive this
	 * information and display
	 * 
	 * @param action
	 *            start with STATUS_
	 */
	private void sendStatus(String action) {
		Intent i = new Intent();
		i.setAction(action);

		Bundle b = new Bundle();

		Singleton singleton = Singleton.getInstance();

		// data send tuy theo action
		if (action.equals(STATUS_BC_NOW_PLAYING) || action.equals(STATUS_BC_ALL)) {
			// b.putParcelable(BKEY_PLAYSONG, playItem);
			singleton.setCurrentSongObject(playItem);
		}

		if (action.equals(STATUS_BC_PLAYTIME) || action.equals(STATUS_BC_ALL)) {
			int pos = 0, dura = 0;
			// Check mediaplayer and state before try to call any method
			if (mMediaPlayer != null && mState != MediaPlayerState.Preparing) {
				pos = mMediaPlayer.getCurrentPosition();
				dura = mMediaPlayer.getDuration();
			}
			b.putInt(BKEY_CURSONG_POSITION, pos);
			b.putInt(BKEY_CURSONG_DURATION, dura);
		}

		if (action.equals(STATUS_BC_PLAYMODE) || action.equals(STATUS_BC_ALL)) {
			if (mPlaylistMgr != null) {
				b.putSerializable(BKEY_REPEATMODE, mPlaylistMgr.getRepeatMode());
				b.putBoolean(BKEY_SHUFFLE, mPlaylistMgr.isShuffle());
			}
		}

		if (action.equals(STATUS_BC_NOWPLAYING_PLAYLIST) || action.equals(STATUS_BC_ALL)) {
			singleton.setPlaylistManager(mPlaylistMgr);
		}

		// state
		b.putSerializable(BKEY_STATE, mState);

		// Put into intent and send broadcast
		i.putExtras(b);
		sendBroadcast(i);
	}

	private void startUpdatePlaytime() {
		mHandler.postDelayed(mUpdateTimeTask, mUpdateInterval);
	}

	private void stopUpdatePlaytime() {
		mHandler.removeCallbacks(mUpdateTimeTask);
	}

	private Runnable mUpdateTimeTask = new Runnable() {

		public void run() {
			sendStatus(STATUS_BC_PLAYTIME);
			mHandler.postDelayed(mUpdateTimeTask, mUpdateInterval);
		}
	};

	/**
	 * Notification Custom Bignotification is available from API 16
	 */
	@SuppressLint("NewApi")
	private void newNotification() {
		RemoteViews simpleContentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notification_custom);
		RemoteViews expandedView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notification_big);
		if (playItem != null) {
			final Notification notification = new NotificationCompat.Builder(getApplicationContext()).setSmallIcon(R.drawable.ic_launcher).setContentTitle(playItem.getTXNAME())
					.build();
			setListeners(simpleContentView);
			setListeners(expandedView);

			Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
			notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
			PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
			notification.contentIntent = pIntent;

			notification.contentView = simpleContentView;
			if (currentVersionSupportBigNotification) {
				notification.bigContentView = expandedView;
			}

			try {
				if (!playItem.getFormNet()) {
					Bitmap b = BitmapFactory.decodeFile(playItem.getAVATAR_SINGER());
					if (b != null) {
						notification.contentView.setImageViewBitmap(R.id.imageViewAlbumArt, b);
						if (currentVersionSupportBigNotification) {
							notification.bigContentView.setImageViewBitmap(R.id.imageViewAlbumArt, b);
						}
						startfore(notification);
					} else {
						notification.contentView.setImageViewResource(R.id.imageViewAlbumArt, R.drawable.ic_launcher);
						if (currentVersionSupportBigNotification) {
							notification.bigContentView.setImageViewResource(R.id.imageViewAlbumArt, R.drawable.ic_launcher);
						}
						startfore(notification);
					}
				} else {
					AppController.getInstance().getImageLoader().get(playItem.getAVATAR_SINGER(), new ImageLoader.ImageListener() {
						@Override
						public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
							Bitmap b = response.getBitmap();
							if (b != null) {
								notification.contentView.setImageViewBitmap(R.id.imageViewAlbumArt, b);
								if (currentVersionSupportBigNotification) {
									notification.bigContentView.setImageViewBitmap(R.id.imageViewAlbumArt, b);
								}
								startfore(notification);
							} else {
								notification.contentView.setImageViewResource(R.id.imageViewAlbumArt, R.drawable.ic_launcher);
								if (currentVersionSupportBigNotification) {
									notification.bigContentView.setImageViewResource(R.id.imageViewAlbumArt, R.drawable.ic_launcher);
								}
								startfore(notification);
							}
						}

						@Override
						public void onErrorResponse(VolleyError arg0) {
							notification.contentView.setImageViewResource(R.id.imageViewAlbumArt, R.drawable.ic_launcher);
							if (currentVersionSupportBigNotification) {
								notification.bigContentView.setImageViewResource(R.id.imageViewAlbumArt, R.drawable.ic_launcher);
								startfore(notification);
							}
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	void startfore(Notification notification) {
		if (mState == MediaPlayerState.Paused) {
			notification.contentView.setViewVisibility(R.id.btnPause, View.GONE);
			notification.contentView.setViewVisibility(R.id.btnPlay, View.VISIBLE);

			if (currentVersionSupportBigNotification) {
				notification.bigContentView.setViewVisibility(R.id.btnPause, View.GONE);
				notification.bigContentView.setViewVisibility(R.id.btnPlay, View.VISIBLE);
			}
		}
		if (mState == MediaPlayerState.Playing) {
			notification.contentView.setViewVisibility(R.id.btnPause, View.VISIBLE);
			notification.contentView.setViewVisibility(R.id.btnPlay, View.GONE);

			if (currentVersionSupportBigNotification) {
				notification.bigContentView.setViewVisibility(R.id.btnPause, View.VISIBLE);
				notification.bigContentView.setViewVisibility(R.id.btnPlay, View.GONE);
			}
		}

		notification.contentView.setTextViewText(R.id.textSongName, playItem.getTXNAME());
		notification.contentView.setTextViewText(R.id.textAlbumName, playItem.getALBUM());
		if (currentVersionSupportBigNotification) {
			notification.bigContentView.setTextViewText(R.id.textSongName, playItem.getTXNAME());
			notification.bigContentView.setTextViewText(R.id.textAlbumName, playItem.getALBUM());
		}
		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		startForeground(NOTIFICATION_ID, notification);
	}

	/**
	 * Notification click listeners
	 * 
	 * @param view
	 */
	public void setListeners(RemoteViews view) {
		Intent previous = new Intent(ACTION_PREVIOUS);
		Intent delete = new Intent(ACTION_DELETE);
		Intent pause = new Intent(ACTION_PAUSE);
		Intent next = new Intent(ACTION_NEXT);
		Intent play = new Intent(ACTION_PLAY);

		PendingIntent pPrevious = PendingIntent.getBroadcast(getApplicationContext(), 0, previous, PendingIntent.FLAG_UPDATE_CURRENT);
		view.setOnClickPendingIntent(R.id.btnPrevious, pPrevious);

		PendingIntent pDelete = PendingIntent.getBroadcast(getApplicationContext(), 0, delete, PendingIntent.FLAG_UPDATE_CURRENT);
		view.setOnClickPendingIntent(R.id.btnDelete, pDelete);

		PendingIntent pPause = PendingIntent.getBroadcast(getApplicationContext(), 0, pause, PendingIntent.FLAG_UPDATE_CURRENT);
		view.setOnClickPendingIntent(R.id.btnPause, pPause);

		PendingIntent pNext = PendingIntent.getBroadcast(getApplicationContext(), 0, next, PendingIntent.FLAG_UPDATE_CURRENT);
		view.setOnClickPendingIntent(R.id.btnNext, pNext);

		PendingIntent pPlay = PendingIntent.getBroadcast(getApplicationContext(), 0, play, PendingIntent.FLAG_UPDATE_CURRENT);
		view.setOnClickPendingIntent(R.id.btnPlay, pPlay);

	}

	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	private void RegisterRemoteClient() {
		remoteComponentName = new ComponentName(getApplicationContext(), new NotificationBroadcast().ComponentName());
		try {
			if (remoteControlClient == null) {
				audioManager.registerMediaButtonEventReceiver(remoteComponentName);
				Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
				mediaButtonIntent.setComponent(remoteComponentName);
				PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);
				remoteControlClient = new RemoteControlClient(mediaPendingIntent);
				audioManager.registerRemoteControlClient(remoteControlClient);
			}
			remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
					| RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
					| RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
		} catch (Exception ex) {
		}
	}

	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	private void UpdateMetadata() {
		if (remoteControlClient == null)
			return;
		final MetadataEditor metadataEditor = remoteControlClient.editMetadata(true);
		metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, playItem.getNAME_SINGERS());
		metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, playItem.getAVATAR_SINGER());
		metadataEditor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, playItem.getTXNAME());

		if (!playItem.getFormNet()) {
			Bitmap bitmap = BitmapFactory.decodeFile(playItem.getAVATAR());
			metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, bitmap);
			metadataEditor.apply();
		} else
			AppController.getInstance().getImageLoader().get(playItem.getAVATAR(), new ImageLoader.ImageListener() {
				@Override
				public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
					Bitmap bitmap = response.getBitmap();
					metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, bitmap);
					metadataEditor.apply();
				}

				@Override
				public void onErrorResponse(VolleyError arg0) {
					metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, null);
					metadataEditor.apply();
				}
			});
		audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
	}

	@Override
	public void onAudioFocusChange(int focusChange) {
	}
}
